package SocketUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 接收socket流发送过来的文件流 使用方法：直接启动即可监控8821端口的情况
 */
public class FileIncepter {
	private int port = 8842;
	private int corePoolSize = 5; // 預線程數
	private int maximumPoolSize = 10; // 開啟的最大線程數
	private long keepAliveTime = 3; // 空閒線程存活時間
	private String filePath = "E:\\test\\"; // 文件存储路径
	
	public FileIncepter(int port, String filePath, int corePoolSize, int maximumPoolSize, long keepAliveTime) {
		super();
		this.port = port;
		this.filePath = filePath;
		this.corePoolSize = corePoolSize;
		this.maximumPoolSize = maximumPoolSize;
		this.keepAliveTime = keepAliveTime;
	}

	public FileIncepter(int port, String filePath) {
		super();
		this.port = port;
		this.filePath = filePath;
	}

	/**
	 * @描述：接收socket发送过来的文件
	 * 
	 * @时间：上午9:10:58
	 * @开发者：稀饭 @测试：通过
	 */
	private void acceptFile(Socket socket) throws IOException {

		DataOutputStream dos = null;
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// 接收文件的文件名
		String fileName = dis.readUTF() + "";
		fileName = editFilePath(fileName);
		long fileLength = dis.readLong();
		createDir(fileName);
		File file = new File(fileName);
		dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
		System.out.println("文件的名字" + fileName);
		System.out.println("开始接收文件!,文件长度是" + fileLength);
		try {
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = dis.read(b)) != -1) {
				dos.write(b, 0, i);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		} finally {
			// 关闭所有连接
			try {
				if (dos != null)
					dos.close();
			} catch (IOException e) {
			}
			try {
				if (dis != null)
					dis.close();
			} catch (IOException e) {
			}
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
			}
		}
	}

	/**
	 * @描述：将传过来的文件名的路径进行修改成本地路径
	 * @时间：下午7:07:09
	 * @开发者：稀饭
	 * @测试：通過
	 * @param
	 */
	public String editFilePath(String path) {
		String index = "\\webapps\\";
		return filePath + path.substring(path.lastIndexOf(index) + index.length(), path.length());
	}

	/**
	 * @描述：
	 * 
	 * @时间：下午7:09:11
	 * @开发者：稀饭 @测试：通过
	 * @param
	 */
	public void createDir(String path) {
		if (path.contains(".")) {
			path = path.substring(0, path.lastIndexOf("\\"));
		}
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
	}

	/**
	 * @描述：创建socket对象
	 * 
	 * @时间：下午2:33:51
	 * @开发者：稀饭 @测试：通过
	 * @param
	 */
	@SuppressWarnings("resource")
	public void createSocket() {
		BlockingQueue<Runnable> linkedBlockingQueue = new ArrayBlockingQueue<Runnable>(4);
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
				TimeUnit.DAYS, linkedBlockingQueue, new ThreadPoolExecutor.CallerRunsPolicy());
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(port);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		while (true) {
			try {
				Socket socket = ss.accept();
				threadPool.execute(new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							acceptFile(socket);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}));
			} catch (IOException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
		}
	}
}
